package src.serverSide;

import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * 
 * @author John Stewart
 * 
 * This class receives messages of the MessageToServer class via the provided port
 * It then executes those messages
 * It also is the central, highest level class for the server, implementing the main class
 */
public class SCom {
	private int port;
	private ExecutorService pool;
	private static final int MAX_CONNECTIONS = 5;
	
	private static Control control = new Control();
	
	public SCom(final int port) {
		this.port = port;
		pool = Executors.newFixedThreadPool(MAX_CONNECTIONS);
	}
	
	/**
	 * @param args This method does not use this input
	 */
	public static void main(String[] args) {
		SCom scom = new SCom(12345);
		scom.run();
	}
	
	/**
	 * This method listens for incoming messages and handles them
	 */
	private void run() {
		ServerSocket server;
		Socket client = null;
		try {
			System.out.println("Server Starting:");
			server = new ServerSocket(port);
			while(true) {
				client = server.accept();
				Handler handler = new Handler(client, control);
				pool.execute(handler);
			}
		} catch (IOException e) {
			System.out.println("Error: In Server Socket Accept");
			e.printStackTrace();
		}
	}
	
}
